package com.lyloou.handler;


import com.lyloou.ApplicationContextHelper;
import com.lyloou.server.RpcRequest;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.lang.reflect.Method;

/**
 * 自定义的业务处理器
 */
public class UserServiceHandler extends ChannelInboundHandlerAdapter {

    //当客户端读取数据时,该方法会被调用
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        //注意:  客户端将来发送请求的时候会传递一个参数
        //1.判断当前的请求是否符合规则
        if (msg instanceof RpcRequest) {
            RpcRequest rr = (RpcRequest) msg;
            Class<?> clazz = Class.forName(rr.getClassName());

            // 从容器中获取bean对象
            Object bean = ApplicationContextHelper.getBean(clazz);

            Method method = clazz.getDeclaredMethod(rr.getMethodName(), rr.getParameterTypes());
            Object result = method.invoke(bean, rr.getParameters());
            ctx.writeAndFlush(result);
        }
    }
}
